package top.appx.service.impl;

import org.springframework.stereotype.Service;
import top.appx.dao.ArticleDao;
import top.appx.entity.ArticleEntity;
import top.appx.qo.ArticleQO;
import top.appx.service.ArticleService;
import top.appx.util.DateTimeUtil;
import top.appx.vo.ArticleVO;
import top.appx.vo.Pager;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zwy on 2015-5-22.
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleDao articleDao;

    public Pager<ArticleVO> queryByPage(ArticleQO bean){
        Pager<ArticleEntity> pager = articleDao.queryByPage(bean,bean.getPage(),bean.getPageSize());
        Pager<ArticleVO> pagerVO = new Pager<ArticleVO>();
        List<ArticleVO> list = new ArrayList<ArticleVO>();
        for (ArticleEntity a:pager.getRows()){
            ArticleVO av = new ArticleVO(a);
            list.add(av);
        }
        pagerVO.setRows(list);
        pagerVO.setTotal(pager.getTotal());
        return pagerVO;
    }
    public List<ArticleVO> homeList(){
        List<ArticleEntity> list = articleDao.homeList();
        List<ArticleVO> listVO = new ArrayList<ArticleVO>();
        for(ArticleEntity a:list) {
            ArticleVO av = new ArticleVO(a);
            listVO.add(av);
        }
        return listVO;
    }
    public void save(ArticleEntity article) {
        article.setUpdateTime(DateTimeUtil.now());
        article.setCreateTime(DateTimeUtil.now());
        article.setCommentCount(0);
        article.setReadCount(0);
        article.setRecommendCount(0);
        articleDao.save(article);
    }

    public void update(ArticleEntity article) {
        ArticleEntity article_new = articleDao.getById(ArticleEntity.class,article.getId());
        article_new.setTitle(article.getTitle());
        article_new.setContent(article.getContent());
        article_new.setUpdateTime(DateTimeUtil.now());
        articleDao.update(article_new);
    }
    public void delById(int id) {
        ArticleEntity article = articleDao.getById(ArticleEntity.class,id);
        articleDao.delete(article);
    }

    public List<ArticleVO> homeNewest(){
        List<ArticleEntity> list = articleDao.homeNewest();
        List<ArticleVO> listVO = new ArrayList<ArticleVO>();
        for(ArticleEntity a:list) {
            ArticleVO av = new ArticleVO(a);
            listVO.add(av);
        }
        return listVO;
    }

    public ArticleVO getById(int id) {
        ArticleEntity article = articleDao.getById(ArticleEntity.class,id);
        return new ArticleVO(article);
    }
}
